{% extends "base.html" %}

{% block content %}
    <h4 style="display: inline;">单子名称：<span id="editWorkflowNname">{{ workflowDetail.workflow_name }}</span></h4>
    &nbsp;&nbsp;&nbsp;
    <input type="hidden" id="workflowDetail_id" name="workflowid" value="{{ workflowDetail.id }}">
    <input type="hidden" id="editSqlContent" value="{{ workflowDetail.sql_content }}"/>
    <input type="hidden" id="editClustername" value="{{ workflowDetail.cluster_name }}"/>
    <input type="hidden" id="editIsbackup" value="{{ workflowDetail.is_backup }}"/>
    <input type="hidden" id="editReviewman" value="{{ listAllReviewMen.0 }}"/>
    <input type="hidden" id="editSubReviewman" value="{{ listAllReviewMen.1 }}"/>
    <input type="hidden" id="sqlMaxRowNumber" value="{{ rows|length }}">
    <hr>
    <table data-toggle="table" class="table table-striped table-hover">
        <thead>
        <tr>
            <th>
                上线发起人
            </th>
            <th>
                审核人
            </th>
            <th>
                上线集群
            </th>
            <th>
                发起时间
            </th>
            <th>
                结束时间
            </th>
            <th>
                是否备份
            </th>
            <th>
                当前状态
            </th>
        </tr>
        </thead>
        <tbody>
        <tr class="success">
            <td>
                {{ workflowDetail.engineer }}
            </td>
            <td>
                {{ listAllReviewMen.0 }} {{ listAllReviewMen.1 }}
            </td>
            <td>
                {{ workflowDetail.cluster_name }}
            </td>
            <td>
                {{ workflowDetail.create_time }}
            </td>
            <td>
                {{ workflowDetail.finish_time }}
            </td>
            <td>
                {{ workflowDetail.is_backup }}
            </td>
            <td>
                {% if workflowDetail.status == "已正常结束" %}
                    <font color="green">
                {% else %}
                    <font color="red">
                {% endif %}
                <B id="workflowDetail_status">{{ workflowDetail.status }}</B></font>
            </td>
        </tr>
        </tbody>
    </table>
    <br>
    <!-- 自定义操作按钮-->
    <div id="detail-toolbar" class="btn-group right">
        <button id="expandAllRows" class="btn btn-default navbar-btn" type="button">展开全部</button>
    </div>
    <table id="tb-detail" data-toggle="table" class="table table-condensed"></table>

    {% if workflowDetail.audit_remark  and workflowDetail.status == '人工终止流程' %}
        <br>
        <table data-toggle="table" class="table table-striped table-hover">
            <thead>
            <tr>
                <th>
                    驳回原因
                </th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>
                    {{ workflowDetail.audit_remark }}
                </td>
            </tr>
            </tbody>
        </table>
        <br>
    {% endif %}
    {% if workflowDetail.status == '定时执行' %}
        <br>
        <table data-toggle="table" class="table table-striped table-hover">
            <thead>
            <tr>
                <th>
                    定时执行时间
                </th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>
                    {{ run_date }}
                </td>
            </tr>
            </tbody>
        </table>
        <br>
    {% endif %}

    {% if workflowDetail.status == '等待审核人审核' %}
        {% if loginUser in listAllReviewMen %}
            <textarea id="remark" name="remark" class="form-control" data-name="审核备注"
                      placeholder="请填写驳回原因" rows=3></textarea>
            <br>

            <form action="/passed/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="submit" id="btnPass" onclick="loading(this)" class="btn btn-danger"
                       value="审核通过"/>
            </form>

            <form id="form-cancel" action="/cancel/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="hidden" id="audit_remark" name="audit_remark" value="">
                <input type="button" id="btnCancel" class="btn btn-default" value="终止流程"/>
            </form>

        {% elif loginUser == workflowDetail.engineer %}
            <form id="form-cancel" action="/cancel/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="hidden" id="audit_remark" name="audit_remark" value="">
                <input type="submit" onclick="loading(this)" class="btn btn-default" value="终止流程"/>
            </form>
        {% endif %}

    {% elif workflowDetail.status == '审核通过' %}
        {% if loginUserOb.role == 'DBA' %}
            <textarea id="remark" name="remark" class="form-control" data-name="审核备注"
                      placeholder="请填写驳回原因" rows=3></textarea>
            <br>

            <form id="from-execute" action="/execute/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="button" id="btnExecute" class="btn btn-danger"
                       value="立即执行"/>
            </form>
            <input type="button" class="btn btn-info" data-toggle="modal" data-target="#cronComfirm" value="定时执行"/>
            <form id="form-cancel" action="/cancel/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="hidden" id="audit_remark" name="audit_remark" value="">
                <input type="button" id="btnCancel" class="btn btn-default" value="终止流程"/>
            </form>

        {% elif loginUser == workflowDetail.engineer %}
            <form id="form-cancel" action="/cancel/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="hidden" id="audit_remark" name="audit_remark" value="">
                <input type="submit" onclick="loading(this)" class="btn btn-default" value="终止流程"/>
            </form>
        {% endif %}

    {% elif workflowDetail.status == '定时执行' %}
        {% if loginUserOb.role == 'DBA' %}
            <textarea id="remark" name="remark" class="form-control" data-name="审核备注"
                      placeholder="请填写驳回原因" rows=3></textarea>
            <br>
            <input type="button" class="btn btn-info" data-toggle="modal" data-target="#cronComfirm" value="执行时间变更"/>
            <form id="form-cancel" action="/cancel/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="hidden" id="audit_remark" name="audit_remark" value="">
                <input type="button" id="btnCancel" class="btn btn-default" value="终止流程"/>
            </form>

        {% elif loginUser == workflowDetail.engineer %}
            <form id="form-cancel" action="/cancel/" method="post" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="hidden" id="audit_remark" name="audit_remark" value="">
                <input type="submit" onclick="loading(this)" class="btn btn-default" value="终止流程"/>
            </form>
        {% endif %}

    {% elif workflowDetail.status == '已正常结束' and workflowDetail.is_backup == '是' %}
        <form action="/rollback/" method="get" style="display:inline-block;">
            {% csrf_token %}
            <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
            <input type="submit" id="btnRollback" onclick="loading(this)" class="btn btn-default" value="查看回滚SQL"/>
        </form>


    {% elif workflowDetail.status == '自动审核不通过' or workflowDetail.status == '人工终止流程' or workflowDetail.status == '执行有异常' %}
        {% if workflowDetail.status == '执行有异常' %}
            <form action="/rollback/" method="get" style="display:inline-block;">
                {% csrf_token %}
                <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                <input type="submit" id="btnRollback" onclick="loading(this)" class="btn btn-default" value="查看回滚SQL"/>
            </form>
        {% endif %}
        {% if loginUser == workflowDetail.engineer %}
            <!--只允许发起人修改工单-->
            {% csrf_token %}
            <a type='button' id="btnEditSql" onclick="loading(this)" class='btn btn-warning' href="/editsql/">重新修改</a>
        {% endif %}
    {% endif %}
    <!-- 定时执行弹出框 -->
    <form id="from-addsqlcronjob" action="/timingtask/" method="post" style="display:inline-block;">
        <div class="modal fade" id="cronComfirm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header ">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">×</span></button>
                        <h4 class="modal-title text-danger">定时执行SQL</h4>
                    </div>
                    {% csrf_token %}
                    <div class="modal-body">
                        <div class="form-group">
                            <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                            <input type="text" class="form-control" id="run_date" name="run_date"
                                   data-format="yyyy-MM-dd hh:mm:ss"
                                   placeholder="请输入执行时间">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-info" data-dismiss="modal">取消</button>

                        <input type="hidden" name="workflowid" value="{{ workflowDetail.id }}">
                        <input type="button" id="btnAddsqlcronjob" class="btn btn-danger" value="确认提交"/>
                    </div>

                </div>
            </div>
        </div>
    </form>

{% endblock content %}

{% block js %}
    {% load staticfiles %}
    <link href="{% static 'datetimepicker/css/bootstrap-datetimepicker.css' %}" rel="stylesheet" type="text/css"/>
    <script src="{% static 'daterangepicker/js/moment.min.js' %}"></script>
    <script src="{% static 'datetimepicker/js/bootstrap-datetimepicker.js' %}"></script>
    <script src="{% static 'datetimepicker/js/bootstrap-datetimepicker.zh-CN.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-export.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/tableExport.min.js' %}"></script>
    <!--初始化时间控件 -->
    <script>
        var date = new Date();
        $("#run_date").datetimepicker({
            format: "yyyy-mm-dd hh:ii:ss",
            autoclose: true,
            todayBtn: true,
            todayHighlight: true,
            showMeridian: false,
            pickerPosition: "bottom-left",
            language: 'zh-CN',//中文，需要引用zh-CN.js包
            startView: 2,//月视图
            minView: 1,//日期时间选择器所能够提供的最精确的时间选择视图
            startDate: date,
            inline: true,
            sideBySide: true
        })
    </script>
    <!--按钮控制 -->
    <script>
        var editWorkflowDetailId = $("#workflowDetail_id").val();
        var editWorkflowNname = $("#editWorkflowNname").text();
        var editSqlContent = $("#editSqlContent").val();
        var editClustername = $("#editClustername").val();
        var editIsbackup = $("#editIsbackup").val();
        var editReviewman = $("#editReviewman").val();
        var editSubReviewman = $("#editSubReviewman").val();

        $("#btnEditSql").click(function () {
            sessionStorage.removeItem('editWorkflowDetailId');
            sessionStorage.setItem('editWorkflowNname', editWorkflowNname);
            sessionStorage.setItem('editSqlContent', editSqlContent);
            sessionStorage.setItem('editClustername', editClustername);
            sessionStorage.setItem('editIsbackup', editIsbackup);
            sessionStorage.setItem('editReviewman', editReviewman);
            sessionStorage.setItem('editSubReviewman', editSubReviewman);
        });
        $("#btnViewSql").click(function () {
            sessionStorage.removeItem('editWorkflowDetailId');
            sessionStorage.setItem('editWorkflowNname', editWorkflowNname);
            sessionStorage.setItem('editSqlContent', editSqlContent);
            sessionStorage.setItem('editClustername', editClustername);
            sessionStorage.setItem('editIsbackup', editIsbackup);
            sessionStorage.setItem('editReviewman', editReviewman);
            sessionStorage.setItem('editSubReviewman', editSubReviewman);
        });
        $("#btnSubmitOtherCluster").click(function () {
            sessionStorage.setItem('editWorkflowNname', editWorkflowNname);
            sessionStorage.setItem('editSqlContent', editSqlContent);
            sessionStorage.setItem('editIsbackup', editIsbackup);
            sessionStorage.setItem('editReviewman', editReviewman);
            sessionStorage.setItem('editSubReviewman', editSubReviewman);
        });

        // 表格展开折叠全部行
        $("#expandAllRows").click(function () {
            if ($(this).text() === '展开全部') {
                $('#tb-detail').bootstrapTable('expandAllRows');
                $(this).text('折叠全部')
            }
            else if ($(this).text() === '折叠全部') {
                $('#tb-detail').bootstrapTable('collapseAllRows');
                $(this).text('展开全部')
            }
        });

        // 执行确认
        $("#btnExecute").click(function () {
            var isContinue = confirm("请确认是否立即执行？");
            var formExecute = $("#from-execute");
            if (isContinue) {
                var element = $(this);
                var sqlNum = element.val();
                formExecute.submit();
                loading(this)
            }
        });

        // 校验备注
        $("#btnCancel").click(function () {
            //获取form对象，判断输入，通过则提交
            $("#audit_remark").val($("#remark").val());
            var formCancel = $("#form-cancel");
            if ($("#audit_remark").val()) {
                $(this).button('loading').delay(2500).queue(function () {
                    $(this).button('reset');
                    $(this).dequeue();
                });
                formCancel.submit();
            }
            else {
                alert('请填写驳回原因')
            }
        });

        // 定时时间校验
        $("#btnAddsqlcronjob").click(function () {
            //获取form对象，判断输入，通过则提交
            var formAddsqlcronjo = $("#from-addsqlcronjob");
            if ($("#run_date").val()) {
                $(this).button('loading').delay(2500).queue(function () {
                    $(this).button('reset');
                    $(this).dequeue();
                });
                formAddsqlcronjo.submit();
            }
            else {
                alert('请填写定时执行时间')
            }
        });

        // 按钮禁用
        function loading(obj) {
            $(obj).button('loading').delay(2500).queue(function () {
                $(obj).button('reset');
                $(obj).dequeue();
            });
        }
    </script>
    <!--osc控制 -->
    <script>
        var workflowid = $("#workflowDetail_id").val();
        var sqlMaxRowNumber = parseInt($("#sqlMaxRowNumber").val());
        var wfStatus = -1;
        var itemIndex = 1;
        var key;
        var isStoped = 0;
        var retryCnt = 1;
        $(document).ready(function () {
            $('#tb-detail').bootstrapTable('destroy').bootstrapTable({
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
                pageSize: 500,                       //每页的记录行数（*）
                pageList: [500, 1000, 10000],        //可供选择的每页的行数（*）
                search: false,                       //是否显示表格搜索
                strictSearch: false,                //是否全匹配搜索
                showColumns: true,                  //是否显示所有的列（选择显示的列）
                showRefresh: false,                  //是否显示刷新按钮
                minimumCountColumns: 1,             //最少允许的列数
                clickToSelect: false,                //是否启用点击选中行
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                toolbar: "#detail-toolbar",         //指明自定义的toolbar
                showExport: true,
                exportDataType: "all",
                detailView: true,                  //是否显示父子表
                //格式化详情
                detailFormatter: function (index, row) {
                    var html = [];
                    $.each(row, function (key, value) {
                        if (key === 'SQL') {
                            var sql = value;
                            //替换所有的换行符
                            sql = sql.replace(/\r\n/g, "<br>");
                            sql = sql.replace(/\n/g, "<br>");
                            //替换所有的空格
                            sql = sql.replace(/\s/g, "&nbsp;");
                            html.push('<span>' + sql + '</span>');
                        }
                    });
                    return html.join('');
                },
                locale: 'zh-CN',                    //本地化
                data:{{ rows|safe }},
                columns: [{
                    title: 'ID',
                    field: 'ID',
                    sortable: true
                }, {
                    title: 'SQL内容',
                    field: 'SQL',
                    formatter: function (value, row, index) {
                        if (value.length > 80) {
                            return value.substr(0, 80) + '...';
                        }
                        else {
                            return value
                        }
                    }
                }, {
                    title: '完整SQL内容',
                    field: 'SQL',
                    visible: false
                }, {
                    title: '审核状态',
                    field: 'errlevel',
                    formatter: function (value, row, index) {
                        if (value === 0) {
                            return 'pass'
                        }
                        else if (value === 1) {
                            return 'warning'
                        }
                        else if (value === 2) {
                            return 'error'
                        }
                    },
                    sortable: true
                }, {
                    title: '审核结果',
                    field: 'errormessage',
                    formatter: function (value, row, index) {
                        return value.replace(/\n/g, '<br>');
                    },
                    sortable: true
                }, {
                    title: '扫描/影响行数',
                    field: 'Affected_rows',
                    sortable: true
                }, {
                    title: '执行耗时',
                    field: 'execute_time',
                    sortable: true
                }, {
                    title: '执行状态',
                    field: 'stagestatus',
                    sortable: true
                }],
                rowStyle: function (row, index) {
                    var style = "";
                    if (row.errlevel === 1) {
                        style = 'warning';
                    }
                    else if (row.errlevel === 2) {
                        style = 'danger';
                    }
                    return {classes: style}
                },
                onLoadSuccess: function () {
                },
                onLoadError: function () {
                    alert("数据加载失败！");
                }
            });

            var status = $("#workflowDetail_status").text();
            var isDetail = window.location.pathname.indexOf("detail");
            if (isDetail != -1 && status === "执行中") {
                get_pct(workflowid, itemIndex);

                $("button").click(function () {
                    var isContinue = confirm("请确认是否中止pt-OSC进程？");
                    if (isContinue) {
                        var element = $(this);
                        var sqlNum = element.val();
                        stopOsc(workflowid, sqlNum);
                    }
                });
            }
        });

        function get_pct(wid, sqlNum) {
            if (sqlNum > sqlMaxRowNumber) {
                getWorkflowStatus(wid);  //最后一条SQL的进度刷新完后，请求后端接口获取整个工单的状态，如果不为“执行中”状态，则提示刷新当前页面；如果是“执行中”，则每隔1秒查询工单的状态，共重试120次
                // console.log('finish1');
                if (wfStatus != -1 && wfStatus != "执行中") {
                    window.location.reload(true);
                }
                else {
                    document.getElementById("workflowDetail_status").innerHTML = "确认中...";
                    if (retryCnt <= 120) {
                        clearTimeout(key);
                        key = setTimeout(function () {
                            get_pct(wid, itemIndex);
                        }, 1000);
                        retryCnt++;
                    }
                    else {
                        retryCnt = 1;
                        alert("该工单2分钟仍然未执行完毕，请稍后尝试手动刷新本页面");
                    }

                }
            }
            else {
                if (isStoped === 1) {
                    document.getElementById("btnstop_" + sqlNum).style.display = "none";
                    return false;
                }
                var pct;
                $.ajax({
                    type: "post",
                    async: false,
                    url: "/getOscPercent/",
                    dataType: "json",
                    data: {
                        workflowid: wid,
                        sqlID: sqlNum
                    },
                    complete: function () {
                    },
                    success: function (data) {
                        //console.log("sqlNum: " + sqlNum);
                        //console.log(data);
                        if (sqlNum <= sqlMaxRowNumber) {
                            if (data.status === -2) {
                                // 整个工单不由pt-OSC执行
                                document.getElementById("td_" + sqlNum).innerHTML = "不由pt-OSC执行";
                                itemIndex++;
                                get_pct(wid, itemIndex);
                                return
                            }
                            else if (data.status === 4) {
                                // 不是由pt-OSC执行的，比如DML语句。
                                document.getElementById("td_" + sqlNum).innerHTML = "不由pt-OSC执行";
                                itemIndex++;
                                clearTimeout(key); //1秒后查询下一行的进度值
                                key = setTimeout(function () {
                                    get_pct(wid, itemIndex);
                                }, 1000)
                            }
                            else if (data.status === -3) {
                                // 进度未知，2秒重试一次，直到工单状态改变
                                getWorkflowStatus(wid);
                                if (wfStatus != -1 && wfStatus === "执行中") {
                                    document.getElementById("div_" + sqlNum).className = "progress";
                                    document.getElementById("div_" + sqlNum).style.width = "100%";
                                    document.getElementById("span_" + sqlNum).innerHTML = "查询中...";
                                    clearTimeout(key);
                                    key = setTimeout(function () {
                                        get_pct(wid, itemIndex);
                                    }, 2000);
                                } else {
                                    // 如果工单状态改变，不是“执行中”，则退出重试
                                    document.getElementById("div_" + sqlNum).style.width = "100%";
                                    document.getElementById("span_" + sqlNum).innerHTML = "未查询到进度";
                                    document.getElementById("div_" + sqlNum).className = "progress";
                                    return false;
                                }
                            }
                            else if (data.status === 0) {
                                // 在inception能查询到它的进度信息，说明正在执行
                                pct = data.data.percent;
                                // console.log('per:' + pct);
                                document.getElementById("div_" + sqlNum).style.width = pct + "%";
                                document.getElementById("div_" + sqlNum).className = "progress-bar";
                                document.getElementById("span_" + sqlNum).innerHTML = pct + "%";
                                if (pct === 100) {
                                    document.getElementById("btnstop_" + sqlNum).style.display = "none";
                                    itemIndex++;
                                    get_pct(wid, itemIndex);
                                } else {
                                    document.getElementById("btnstop_" + sqlNum).style.display = "";
                                    clearTimeout(key);
                                    key = setTimeout(function () {
                                        get_pct(wid, itemIndex);
                                    }, 800)
                                }
                            }
                            else {
                                alert(data.msg);
                                return;
                            }
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            }
        }

        function stopOsc(wid, sqlNum) {
            if (wid > 0 && sqlNum >= 1 && sqlNum <= sqlMaxRowNumber) {
                //console.log('stoping osc...'+ sqlNum);
                $.ajax({
                    type: "post",
                    async: false,
                    url: "/stopOscProgress/",
                    dataType: "json",
                    data: {
                        workflowid: wid,
                        sqlID: sqlNum
                    },
                    complete: function () {
                    },
                    success: function (data) {
                        //console.log(data);
                        if (data.status === 0) {
                            //改变全局变量isStoped的值，以便停止进度条更新
                            isStoped = 1;
                        }
                        alert(data.msg);
                        window.location.reload(true);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            }
        }

        function getWorkflowStatus(wid) {
            if (wid > 0) {
                // console.log('get workflow status');
                $.ajax({
                    type: "post",
                    async: false,
                    url: "/getWorkflowStatus/",
                    dataType: "json",
                    data: {
                        workflowid: wid
                    },
                    complete: function () {
                    },
                    success: function (data) {
                        wfStatus = data.status;
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            }
            else {
                alter("参数不正确")
            }
        }
    </script>
{% endblock %}
